package Java_Concurrency_in_Practice.c6_3_1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class FutureRender {
    private final ExecutorService executor = null;

    void renderPage(CharSequence source) {
        final List<ImageInfo> imageInfos = RenderUtil.scanForImageInfo(source);
        Callable<List<ImageData>> task = new Callable<List<ImageData>>() {
            @Override
            public List<ImageData> call() throws Exception {
                List<ImageData> result = new ArrayList<>();
                for (ImageInfo info : imageInfos) {
                    result.add(info.downloadImage());
                }
                return result;
            }
        };
        Future<List<ImageData>> future = executor.submit(task);
        RenderUtil.renderText(source);

        try {
            List<ImageData> imageDatas = future.get();
            for (ImageData image : imageDatas) {
                RenderUtil.renderImage(image);
            }
        } catch (InterruptedException e) {
            // 重新设置线程的中断状态
            Thread.currentThread().interrupt();
            // 由于不需要结果, 因此取消任务
            future.cancel(true);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }

}
